function convertPercentagesToFloats(arr) {
    return arr.map(str => {
        if (typeof str === 'string') {
            // 去除百分号
            const numberStr = str.replace('%', '');
            // 将字符串转换为浮点数
            const floatValue = parseFloat(numberStr);
            // 将浮点数除以 100 得到小数形式
            return floatValue / 100;
        }
        // 如果不是字符串，返回 null 或者其他默认值
        return null;
    });
}
export function check_alarm(conf,max_frame_count,recentFireConf,recentSmokeConf,fire_conf_proportion,smoke_conf_proportion,proportion_threshold){
    var fire_len = recentFireConf.length;
    var smoke_len = recentSmokeConf.length;
    //console.log(conf)
    // conf_list 是一帧的。。
    //for(var conf in conf_list){
    //    console.log(conf)
        //检查fire的置信度，是一个array
        //console.log(conf);
    if(conf['fire'].length === 0){
        //console.log("conf fire is 0");
        if(fire_len === max_frame_count){
            recentFireConf.shift();
        }
        //直接赋值
        recentFireConf.push([-1]);
    }else{
        //console.log("conf fire is not 0");
        if(fire_len === max_frame_count){
            recentFireConf.shift();
        }
        recentFireConf.push(convertPercentagesToFloats(conf['fire']));
    }
    if(conf['smoke'].length === 0){
        if(smoke_len === max_frame_count){
            recentSmokeConf.shift();
        }
        //直接赋值
        recentSmokeConf.push([-1]);
    }else{
        if(smoke_len === max_frame_count){
            recentSmokeConf.shift();
        }
        recentSmokeConf.push(convertPercentagesToFloats(conf['smoke']));
    }
    //准备工作完成。
    //计算比例
    var smoke_alarm_count = 0;
    var fire_alarm_count = 0;
    //console.log(recentFireConf);
    //console.log(recentSmokeConf);
    // 如果最近帧的置信度已经满了，就进行审核。
    if(recentFireConf.length === max_frame_count){
        //console.log("计算最近的火焰满足度",recentFireConf);
        for(let i = 0; i < recentFireConf.length; i++) {
            const conf_fire_list = recentFireConf[i];
            for(let conf_fire of conf_fire_list){
                //console.log(conf_fire,fire_conf_proportion,conf_fire>=fire_conf_proportion);
                if(conf_fire >= fire_conf_proportion){
                    fire_alarm_count++;
                    break;
                }
            }
        }
    }
    if(recentSmokeConf.length === max_frame_count){
        //console.log("计算最近的烟雾满足度",recentSmokeConf);
        for (let i = 0; i < recentSmokeConf.length; i++) {
            const conf_smoke_list = recentSmokeConf[i];
            for (let conf_smoke of conf_smoke_list) {
                //console.log(conf_smoke,smoke_conf_proportion,conf_smoke>=smoke_conf_proportion);
                if (conf_smoke >= smoke_conf_proportion) {
                    smoke_alarm_count++;
                    break;
                }
            }
        }
    }
    //console.log(fire_alarm_count,smoke_alarm_count);
    var fire_result = fire_alarm_count/max_frame_count;
    var smoke_result = smoke_alarm_count/max_frame_count;
    console.log(fire_result,smoke_result);
    var result = {'fire':0,'smoke':0}
    if(fire_result>proportion_threshold){
        result['fire'] = 1;
    }
    if(smoke_result  > proportion_threshold){
        result['smoke'] = 1;
    }
    return result;
}
// 睡眠函数
export function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

export function showNotification(message, type = 'primary', duration = 3000) {
    // 创建通知元素
    const notification = document.createElement('div');

    // 设置通知样式和内容
    const iconMap = {
        primary: 'fa-info-circle',
        success: 'fa-check-circle',
        warning: 'fa-exclamation-triangle',
        danger: 'fa-times-circle'
    };

    const colorMap = {
        primary: 'bg-primary text-white',
        success: 'bg-success text-white',
        warning: 'bg-warning text-white',
        danger: 'bg-danger text-white'
    };

    notification.className = `
        ${colorMap[type]}
        rounded-lg
        px-6
        py-4
        flex
        items-center
        gap-3
        max-w-md
        w-full
        mx-4
        notification-shadow
        animate-fade-in
        relative
    `;

    notification.innerHTML = `
        <i class="fa-solid ${iconMap[type]} text-xl"></i>
        <p class="flex-1 text-[clamp(1rem,2vw,1.125rem)] font-medium">${message}</p>
        <button class="close-btn text-white/80 hover:text-white transition-colors">
          <i class="fa-solid fa-times"></i>
        </button>
        `;

    // 添加进度条
    const progressBar = document.createElement('div');
    progressBar.className = `absolute bottom-0 left-0 h-1 w-full bg-white/30 overflow-hidden`;

    const progressFill = document.createElement('div');
    progressFill.className = `h-full bg-white/70 transition-all duration-[${duration}ms] ease-linear w-full`;

    progressBar.appendChild(progressFill);
    notification.appendChild(progressBar);

    // 添加到容器
    const container = document.getElementById('notification-container');
    container.appendChild(notification);

    // 开始进度条动画
    setTimeout(() => {
        progressFill.style.width = '0';
    }, 10);

    // 设置自动关闭
    const closeNotification = () => {
        notification.classList.add('animate-fade-out');
        setTimeout(() => {
          container.removeChild(notification);
        }, 500);
    };

    // 点击关闭按钮
    notification.querySelector('.close-btn').addEventListener('click', closeNotification);

    // 超时自动关闭
    setTimeout(closeNotification, duration);

    // 点击通知也可以关闭
    notification.addEventListener('click', (e) => {
    if (e.target !== notification) return;
        closeNotification();
    });

    return notification;
}

// JSON文件解析函数
// 解析摄像头配置JSON文件的异步函数，返回Promise对象
export function parseCameraConfig(file) {
    return new Promise((resolve, reject) => {
        // 创建FileReader对象用于读取文件内容
        const reader = new FileReader();

        // 监听onload事件，当文件读取完成时触发
        reader.onload = (e) => {
            try {
                // 解析文件内容为JSON对象
                const config = JSON.parse(e.target.result);

                // 验证配置对象是否包含cameras数组
                if (!Array.isArray(config.cameras)) {
                    // 若格式不符合，抛出错误
                    throw new Error("配置文件格式错误，缺少cameras数组");
                }

                // 验证通过，将解析后的配置对象作为Promise成功结果返回
                resolve(config);
            } catch (error) {
                // 捕获解析过程中的异常（如JSON格式错误）
                reject(`解析失败：${error.message}`);
            }
        };

        // 监听onerror事件，当文件读取过程中发生错误时触发
        reader.onerror = (error) => {
            // 将错误信息作为Promise失败结果返回
            reject(`文件读取失败：${error.message}`);
        };

        // 启动异步文件读取操作，以文本形式读取
        reader.readAsText(file);
    });
}
// 获取视频输入设备并生成JSON文件
export function getVideoDevicesAndGenerateJSON() {
    return new Promise((resolve, reject) => {
        if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
            navigator.mediaDevices.enumerateDevices()
               .then((devices) => {
                    const videoDevices = devices.filter(device => device.kind === 'videoinput');
                    const jsonData = {
                        cameras: videoDevices.map(device => ({
                            id: device.deviceId,
                            label: device.label,
                            room: '未知'
                        }))
                    };
                    const jsonBlob = new Blob([JSON.stringify(jsonData, null, 2)], { type: 'application/json' });
                    const url = URL.createObjectURL(jsonBlob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'camera_devices.json';
                    a.click();
                    URL.revokeObjectURL(url);
                    resolve();
                })
               .catch((error) => {
                    reject(`获取设备失败：${error.message}`);
                });
        } else {
            reject('浏览器不支持获取视频输入设备');
        }
    });
}
export function read_text(text){
    if ('speechSynthesis' in window) {
      // 支持语音合成
        const synth = window.speechSynthesis;
        // 创建语音请求
        const utterance = new SpeechSynthesisUtterance(text);
        // 设置参数（可选）
        utterance.lang = 'zh-CN';  // 语言代码（中文）
        utterance.rate = 3;        // 语速（默认1）
        utterance.pitch = 10;       // 音调（默认1）
        utterance.volume = 10;      // 音量（默认1）
        // 开始播报
        synth.speak(utterance);
    } else {
      // 不支持，提供备选方案
        console.log("不支持");
    }
}